﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;

namespace Batch_Torrent_Downloader
{
    public static class Program
    {
        

        public static void Main()
        {
            var applicationPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            Console.WriteLine(" ~ ~ ~ ~ Batch Torrent Downloader v0.0.1.0 ~ ~ ~ ~ ");
            Console.WriteLine(" ~ ~ ~ ~ (C)2012 REED I.T. All rights reserved. [Lockport, NY] ~ ~ ~ ~");
            if (File.Exists(applicationPath + "\\MovieList.txt"))
            {
                var count = File.ReadLines(applicationPath + "\\MovieList.txt").Count();
                Console.WriteLine(" > Movie List Length: {0}",count);
                if (count <= 1)
                {
                    Console.WriteLine(" -> Please Add Movies to the Movie List then Restart! <-  [ENTER]");
                    Console.ReadLine();
                    Environment.Exit(0);
                }
            }
            else
            {
                File.Create(applicationPath + "\\MovieList.txt");
                Console.WriteLine("Movie List File Not Found, Created! Press [ENTER] to Close. Restart Application!");
                Console.ReadLine();
                Environment.Exit(0);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Press [ENTER] to begin batch download.....");
            Console.ReadLine();

            using (var reader = new StreamReader(applicationPath + "\\MovieList.txt"))
            {
                while (!reader.EndOfStream)
                {
                    var movieName = reader.ReadLine();
                    if (movieName == null) continue;

                    var searchString = movieName.Replace(" ", "+");

                    Console.WriteLine(GetValue(searchString)
                                          ? " ~ Movie Downloaded Successfully ~"
                                          : " ~ Failed to Find Movie ~");
                    Thread.Sleep(500);
                }
            }
            Console.WriteLine(" > Process Complete");
            Console.WriteLine("Press [ENTER] to Exit....");
            Console.ReadLine();
        }

        private static bool GetValue(string searchString)
        {
            using (var webClient = new WebClient())
            {
                webClient.Headers["User-Agent"] =
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6";

                var torrentzData = webClient.DownloadString("http://torrentz.eu/search?f=" + searchString);

                Console.WriteLine(" > Checking Torrentz ...");
                var torrentzLink = GetTorrentzLink(torrentzData);

                Console.WriteLine(" > Getting Torrentz Link ...");
                var torrentzListData = webClient.DownloadString("http://torrentz.eu/" + torrentzLink);

                Console.WriteLine(" > Getting BitSnoop Link ...");
                var bitsnoopLink = GetBitSnoopTorrentLink(torrentzListData);

                if (bitsnoopLink == null)
                {
                    Console.WriteLine(" > > Cannot Find a BitSnoop Link ... Skipping");
                    return false;
                }

                Console.WriteLine(" > Getting Magnet Link ...{0}", bitsnoopLink);
                var bitsnoopData = webClient.DownloadString(bitsnoopLink);
                var magnetUri = GetBitSnoopMagnetLink(bitsnoopData);

                if (magnetUri == null)
                {
                    return false;
                }
                Console.WriteLine(" > Adding Torrent ...");
                Process.Start(magnetUri);
                return true;
            }
        }


        private static string GetBitSnoopTorrentLink(string pageData)
        {
            const string torrentLinkRegex = @"<a href=""(?<Link>http://bitsnoop\.com/.+?-q\d{1,10}?\.html)""";

            return Regex.IsMatch(pageData, torrentLinkRegex) ? Regex.Match(pageData, torrentLinkRegex).Groups["Link"].Value : null;
        }

        private static string GetBitSnoopMagnetLink(string pageData)
        {
            const string magnetRegex = @"""(?<Link>magnet\:\?xt=urn\:btih\:.*)\"" title=""Magnet Link""";

            return Regex.IsMatch(pageData, magnetRegex) ? Regex.Match(pageData, magnetRegex).Groups["Link"].Value : null;
        }

        private static string GetTorrentzLink(string pageData)
        {
            const string magnetRegex = @"<a href=""/(?<Link>\w{20,50}?)"">";

            return Regex.IsMatch(pageData, magnetRegex) ? Regex.Match(pageData, magnetRegex).Groups["Link"].Value : null;
        }

    }
}
